<template>
  <el-drawer direction="rtl"  :title="dialogTitle" v-model="dialogVisible" size="1200px">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="楼栋地址">
            {{netHouseAccountMapData.houseName}}
            <!-- <span style="color:red; margin-left: 10px;">抽取新账号会自动设置最新分账规则到新账号</span>
            <span style="color:green; margin-left: 10px;">同步账号人员仅同步人员信息不更新分账内容</span> -->
          </el-form-item>
          <el-form-item label="" prop="keyWord">
            <el-input placeholder="请输入内容" v-model.trim="keyWord">
              <template #prepend>
                <el-select v-model="kType" placeholder="请选择" class="!w-120px">
                  <el-option label="用户姓名" value="userName" />
                  <el-option label="用户身份证号码" value="userCertno" />
                  <el-option label="用户手机" value="userTelphone" />
                  <el-option label="宽带账号" value="netAccount" />
                  <el-option label="地址" value="addrRemark" />
                  <el-option label="分账账户1" value="mateAccount1" />
                  <el-option label="分账账户2" value="mateAccount2" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <!-- <el-button
              type="primary"
              plain
              @click="syncLfAccountByInsert()"
              v-hasPermi="['zwsj:net-house-account-map:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 抽取新账号
            </el-button>
            <el-button
              type="primary"
              plain
              @click="syncLfAccountByUpdate()"
              v-hasPermi="['zwsj:net-house-account-map:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 同步账号人员
            </el-button>
            
            <el-dropdown @command="handleCommand" v-hasPermi="['zwsj:net-house-account-map:create']">
              <el-button type="primary">
                更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
                <template #dropdown  >
                  <el-dropdown-menu>
                    <el-dropdown-item command="copyAll">全部覆盖分账规则</el-dropdown-item>
                    <el-dropdown-item command="copyDivideMat1">覆盖分账账户1</el-dropdown-item>
                    <el-dropdown-item command="copyDivideMat2">覆盖分账账户2</el-dropdown-item>
                    <el-dropdown-item command="copyUnderTake">覆盖兜底账户</el-dropdown-item>
                    <el-dropdown-item command="export">导出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
            </el-dropdown> -->
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="编号" align="center" prop="id" width="60"/>
          <el-table-column label="用户" align="left" prop="userName" min-width="300">
            <template #default="scope">
              <div>地址：{{ scope.row.addrRemark }}</div>
              <div>账号：<Icon icon="ep:refresh"  style="color:green;" @click="refreshAccountFromLf(scope.row.id)"/>{{ scope.row.netAccount }} </div>
              <div>姓名：{{ scope.row.userName}}（{{ scope.row.userTelphone }}）</div>
              <div>证号：{{ scope.row.userCertno }}</div>
            </template>
          </el-table-column>
          <el-table-column label="分账" align="left" width="270">
            <template #default="scope">
              <div>模式：<dict-tag :type="DICT_TYPE.NET_DIVIDE_MODE" :value="scope.row.divideMode"/></div>
              <div>账户1：{{scope.row.divideMatUserName1_}}，{{ scope.row.divideMatValue1 }}</div>
              <div>账户2：{{scope.row.divideMatUserName2_}}，{{ scope.row.divideMatValue2 }}</div>
              <div>兜底：{{scope.row.underTakeMatCode }}</div>
            </template>
          </el-table-column>
          <el-table-column label="下单时间/联动账号" align="left" width="190">
            <template #default="scope">
              <div>{{ formatDate(scope.row.createTime) }}</div>
              <div v-for="(link) in scope.row.linkAccounts" :key="link.id">{{link.linkAccount}}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['zwsj:net-house-account-map:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['zwsj:net-house-account-map:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
  </el-drawer>  

  <!-- 表单弹窗：添加/修改 -->
  <NetAccountMapForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter,formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { NetAccountMapApi, NetAccountMapVO } from '@/api/zwsj/netaccountmap'
import { NetHouseAccountMapApi, NetHouseAccountMapVO } from '@/api/zwsj/nethouseaccountmap'
import NetAccountMapForm from './NetAccountMapForm.vue'

/** 宽带账号分账 列表 */
defineOptions({ name: 'NetAccountMap' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题

const loading = ref(true) // 列表的加载中
const list = ref<NetAccountMapVO[]>([]) // 列表的数据
// 列表的总页数
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  houseMapId: undefined,
  userName: '',
  userCertno: '',
  userTelphone: '',
  netAccount: '',
  addrRemark: '',
  mateAccount1: '',
  mateAccount2: '',
})

const keyWord = ref('')
const kType = ref('userTelphone')

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const initKeyWord = async () =>{
  queryParams.userName = ''
  queryParams.userCertno = ''
  queryParams.userTelphone = ''
  queryParams.netAccount = ''
  queryParams.addrRemark = ''
  queryParams.mateAccount1 = ''
  queryParams.mateAccount2 = ''

  if ('userName' == kType.value) {
    queryParams.userName = keyWord.value
  } else if ('userCertno' == kType.value) {
    queryParams.userCertno = keyWord.value
  }else if ('userTelphone' == kType.value) {
    queryParams.userTelphone = keyWord.value
  }else if ('netAccount' == kType.value) {
    queryParams.netAccount = keyWord.value
  }else if ('addrRemark' == kType.value) {
    queryParams.addrRemark = keyWord.value
  }else if ('mateAccount1' == kType.value) {
    queryParams.mateAccount1 = keyWord.value
  }else if ('mateAccount2' == kType.value) {
    queryParams.mateAccount2 = keyWord.value
  }
}

/** 打开弹窗 */
const open = async (houseMapId: number) => {
  dialogVisible.value = true
  dialogTitle.value = '楼栋账号管理'
  queryParams.houseMapId = houseMapId

  //查询楼栋地址
  getHouseMapData(houseMapId)
  //查询楼栋下账户信息
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const netHouseAccountMapData = ref({
  houseId: undefined,
  houseName: undefined,
})
const getHouseMapData = async (houseMapId: number) =>{
  const data = await NetHouseAccountMapApi.getNetHouseAccountMap(houseMapId)
  netHouseAccountMapData.value = data
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    initKeyWord()
    const data = await NetAccountMapApi.getNetAccountMapPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await NetAccountMapApi.deleteNetAccountMap(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await NetAccountMapApi.exportNetAccountMap(queryParams)
    download.excel(data, '宽带账号分账.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const refreshAccountFromLf = async (id: number) => {
   await message.confirm('将从计费系统更新[该用户]账户信息')
    await  NetAccountMapApi.updateNetAccountFromLfByMapId(id);
    message.success(t('common.success'))
    handleQuery()
}

const syncLfAccountByInsert = async () => {
   await message.confirm('将从计费系统抽取[本楼栋]新账户信息')
    await  NetHouseAccountMapApi.cerateNetAccountFromLfByHouseMapId(queryParams.houseMapId);
    message.success('抽取成功')
    handleQuery()
}

const syncLfAccountByUpdate = async () => {
   await message.confirm('将从计费系统更新[本楼栋所有用户]账户信息')
    await  NetHouseAccountMapApi.updateNetAccountFromLfByHouseMapId(queryParams.houseMapId);
    message.success('更新成功')
    handleQuery()
}

const handleCommand = async (command: string | number | object) => {
  handleQuery()
  if(command == 'copyAll'){
    await message.confirm('将使用楼栋配置的规则覆盖本楼栋下所有宽带账号')
    await  NetHouseAccountMapApi.copyHouseDivideToAccounts(queryParams.houseMapId,command);
    message.success('更新成功')
  }else if(command == 'copyDivideMat1'){
    await message.confirm('将使用楼栋配置的分账账户1规则覆盖本本楼栋下所有宽带账号')
    await  NetHouseAccountMapApi.copyHouseDivideToAccounts(queryParams.houseMapId,command);
    message.success('更新成功')
  }else if(command == 'copyDivideMat2'){
    await message.confirm('将使用楼栋配置的分账账户2规则覆盖本本楼栋下所有宽带账号')
    await  NetHouseAccountMapApi.copyHouseDivideToAccounts(queryParams.houseMapId,command);
    message.success('更新成功')
  }else if(command == 'copyUnderTake'){
    await message.confirm('将使用楼栋配置的兜底账户覆盖本本楼栋下所有宽带账号')
    await  NetHouseAccountMapApi.copyHouseDivideToAccounts(queryParams.houseMapId,command);
    message.success('更新成功')
  }
    handleQuery()
}

</script>